'use client';

import { useState } from 'react';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger } from '../ui/select';

export default function MultiSelector({
  items,
  value,
  onChange,
}: {
  items: {
    label: string;
    value: string;
  }[];
  value: string[];
  onChange: (value: string[]) => void;
}) {
  const selected = items.filter((i) => value.includes(i.value));
  const itemsToShow = items.filter((i) => !value.includes(i.value));
  const [open, setOpen] = useState(false);
  return (
    <Select
      open={open}
      value=""
      onOpenChange={setOpen}
      onValueChange={(newValue) => onChange([...value, newValue])}
    >
      <div
        className="relative bg-transparent flex flex-wrap items-center px-2 py-1 gap-2 rounded-md border min-w-40 max-w-80 min-h-9"
        onClick={() => setOpen(true)}
      >
        <SelectTrigger className="w-0 h-0 p-0 m-0 border-none absolute invisible bottom-0 " />
        {selected.length ? (
          selected.map((i) => (
            <Badge key={i.value}>
              {i.label}
              <span
                className="i-ri-close-line ml-1 cursor-pointer"
                onClick={(e) => {
                  e.stopPropagation();
                  onChange(value.filter((j) => j !== i.value));
                }}
              />
            </Badge>
          ))
        ) : (
          <span className="text-muted-foreground text-sm">请选择...</span>
        )}
      </div>
      <SelectContent>
        {itemsToShow.length ? (
          itemsToShow.map((item) => (
            <SelectItem key={item.value} value={item.value}>
              {item.label}
            </SelectItem>
          ))
        ) : (
          <div className="p-2 text-sm">没有更多了...</div>
        )}
      </SelectContent>
    </Select>
  );
}
